package com.zzmcc.jms.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.kit.PoiExt;
import com.jfinal.ext.render.excel.JxlsRender;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.zzmcc.base.BaseController;
import com.zzmcc.common.AuthorizeInterceptor;
import com.zzmcc.jms.model.Demand;
import com.zzmcc.jms.model.DemandScreen;
import com.zzmcc.jms.model.Project;
import com.zzmcc.sys.model.Userinfo;
import util.ChristStringUtil;
import util.ModelUtils;
import util.StringUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.zzmcc.jms.common.ModelConfigWms.TABLE_Demand;
import static com.zzmcc.jms.common.ModelConfigWms.TABLE_Project;

/**
 * 筛查管理
 */

public class DemandScreenController extends BaseController {
    private static final Logger log =  Logger.getLogger(DemandScreenController.class);

	public void index() {

        StringBuffer whee = new StringBuffer();
        List<Object> param = new ArrayList<Object>();

        String name = getPara("demand.name");
		String demandMemo = getPara("demand.demandMemo");
		String isScreen = getPara("demand.isScreen");
		String isConfirm = getPara("demand.isConfirm");
		String cusName = getPara("demand.cusName");
		String homeCounty = getPara("demand.homeCounty");

        if(ChristStringUtil.isNotEmpty(name)){
            whee.append(" and name like ?");
            param.add("%" + name + "%");
        }

		if(ChristStringUtil.isNotEmpty(demandMemo)){
			whee.append(" and demandMemo like ?");
			param.add("%" + demandMemo + "%");
		}

		if(ChristStringUtil.isNotEmpty(cusName)){
			whee.append(" and cusName = ?");
			param.add(cusName);
		}

		if(ChristStringUtil.isNotEmpty(homeCounty)){
			whee.append(" and homeCounty = ?");
			param.add(homeCounty);
		}
		if(ChristStringUtil.isNotEmpty(isScreen)){
			whee.append(" and coalesce(b.isScreen,'否') = ?");
			param.add(isScreen);
		}
		if(ChristStringUtil.isNotEmpty(isConfirm)){
			whee.append(" and coalesce(isConfirm,'否') = ?");
			param.add(isConfirm);
		}

		Page<DemandScreen> pager = DemandScreen.dao.paginate(
				getParaToInt("pageNum", 1),
				getParaToInt("numPerPage", 20),
				"select a.id,a.did,a.cusName,a.homeCounty,a.name,a.longitude,a.latitude,a.aerialHeight,a.isConfirm,a.confirmDate," +
						"b.isScreen,b.createDate screenDate,b.isSuccess,b.failMemo,b.isShare,b.memo,b.modifyDate ",
				" from jms_demand a left join jms_demand_screen b on b.did=a.did " +
						" where a.isValid='是'  "+ whee.toString()+" order by b.modifyDate desc",
				param.toArray());

		setAttr("pager",pager);
		setAttr("name",name);
		setAttr("demandMemo",demandMemo);
		setAttr("cusName",cusName);
		setAttr("isScreen",isScreen);
		setAttr("isConfirm",isConfirm);
		setAttr("homeCounty",homeCounty);
		render("../demand_screen_list.html");

	}

	/**
	 * 站址筛查
	 */
	@Before(AuthorizeInterceptor.class)
	public void add() {
		String id = getPara("id");
		Userinfo loginUser =getSessionAttr("loginUser");
		String homeCounty=loginUser.get("homeCounty");
		String modifyUser=loginUser.get("realname");
		int roleid=loginUser.get("roleid");

		String sql="select a.id aid,a.did,a.cusName,a.homeCounty,a.ctName,a.name,a.longitude,a.latitude,a.aerialHeight,a.isConfirm," +
				"b.id bid,b.isScreen,b.isSuccess,b.failMemo,b.isShare,b.buildType,b.memo" +
				" from jms_demand a left join jms_demand_screen b on b.did=a.did " +
				" where a.id=?";
		DemandScreen m= DemandScreen.dao.findFirst(sql, id);
		//管理员及区域负责人才有权限修改
		if (roleid==0||(StringUtil.isNotEmpty(homeCounty)&&homeCounty.equals(m.get("homeCounty")))
				||(m.get("homeCounty").equals("台投")&&modifyUser.equals("李育纯"))){
			setAttr("modifyUser",modifyUser);
			setAttr("roleid",roleid);
			setAttr("demandScreen",m);
			render("../demand_screen_input.html");
		} else {
			render("../project_operate_tip.html");
		}

	}

	/**
	 * 筛查信息保存
	 */

	public void save() {
		try {
			DemandScreen s = getModel(DemandScreen.class, "demandScreen");
			ModelUtils.fillForUpdate(s);
			if (s.get("id")==null)
				s.save();
			else
				s.update();
			//去掉筛查确认环境，如果筛查，直接更新
			//修改时间16-4-21
			String isScreen = s.getStr("isScreen");

			Demand m= getModel(Demand.class,"demand");
			String isConfirm= m.getStr("isConfirm");
			if (StringUtil.isNotEmpty(isScreen) && isScreen.equals("是")  && StringUtil.isEmpty(isConfirm)){
				m.set("isConfirm", "是");
				m.set("confirmDate",new Date());
				ModelUtils.fillUUID(m,"pid");
			}
			ModelUtils.fillForUpdate(m);
			m.update();
			renderDWZSuccessJson("筛查信息更新成功！");

		}catch (Exception e){
			renderDWZSuccessJson("重复提交失败！");
		}

	}

	@Before(AuthorizeInterceptor.class)
	public void edit() {
		//筛查确认
		String id = getPara("id");
		String[] ids = getParaValues("id");
		Userinfo loginUser =getSessionAttr("loginUser");
		String modifyUser=loginUser.get("realname");
		int roleid=loginUser.get("roleid");

		String sql="select a.id,a.did,a.cusName,a.homeCounty,a.ctName,a.name,a.longitude,a.latitude,a.aerialHeight,a.isConfirm," +
				"b.isSuccess,b.failMemo,b.isShare,b.memo" +
				" from jms_demand a left join jms_demand_screen b on b.did=a.did " +
				" where a.id=?";
		DemandScreen m= DemandScreen.dao.findFirst(sql, id);
		setAttr("modifyUser",modifyUser);
		setAttr("roleid",roleid);
		setAttr("demandScreen",m);
		render("../demand_confirm_input.html");


	}

	public void updateConfirm() {

		Demand m = getModel(Demand.class, "demand");
		//更新状态，同时更新完成时间
		String isConfirm = m.getStr("isConfirm");
		if (StringUtil.isNotEmpty(isConfirm) && isConfirm.equals("是")){
			m.set("isConfirm", "是");
			m.set("confirmDate",new Date());
			ModelUtils.fillUUID(m,"pid");
		}
		ModelUtils.fillForUpdate(m);
		m.update();
		renderDWZSuccessJson("筛查确认成功！");
	}

	//@Before(AuthorizeInterceptor.class)
	public void transConfirm() {
		//需求确认
		String[] ids = getParaValues("ids");
		for(String id:ids) {
			Demand m = Demand.dao.findById(id);
			String isConfirm = m.getStr("isConfirm");
			if ( StringUtil.isEmpty(isConfirm)||isConfirm.equals("否")){
				m.set("isConfirm", "是");
				m.set("confirmDate",new Date());
				ModelUtils.fillUUID(m,"pid");
			}
			ModelUtils.fillForUpdate(m);
			m.update();
		}
		renderDWZSuccessJson("筛查确认批量处理成功!");

	}
	public void export() {

		StringBuffer whee = new StringBuffer();
		List<Object> param = new ArrayList<Object>();

		String name = getPara("demand.name");
		String cusName = getPara("demand.cusName");
		String demandMemo = getPara("demand.demandMemo");
		String isScreen = getPara("demand.isScreen");
		String isConfirm = getPara("demand.isConfirm");
		String homeCounty = getPara("demand.homeCounty");

		if(ChristStringUtil.isNotEmpty(name)){
			whee.append(" and name like ?");
			param.add("%" + name + "%");
		}

		if(ChristStringUtil.isNotEmpty(cusName)){
			whee.append(" and cusName = ?");
			param.add(cusName);
		}

		if(ChristStringUtil.isNotEmpty(demandMemo)){
			whee.append(" and demandMemo like ?");
			param.add("%" + demandMemo + "%");
		}


		if(ChristStringUtil.isNotEmpty(homeCounty)){
			whee.append(" and homeCounty = ?");
			param.add(homeCounty);
		}
		if(ChristStringUtil.isNotEmpty(isScreen)){
			whee.append(" and coalesce(isScreen,'否') = ?");
			param.add(isScreen);
		}
		if(ChristStringUtil.isNotEmpty(isConfirm)){
			whee.append(" and coalesce(isConfirm,'否') = ?");
			param.add(isConfirm);
		}

		/**
		 * 清单
		 */
		String sql="select a.id,a.did,a.cusName,a.city,a.homeCounty,a.name,a.longitude,a.latitude,a.aerialHeight," +
				"b.isSuccess,b.failMemo,b.isShare,b.shareName,b.longitude longitude2,b.latitude latitude2,b.addr,\n" +
				"b.space,b.aerialHeight aerialHeight2,b.aerialCnt,b.towerType,b.room,b.buildType,b.memo\n"+
				" from jms_demand a\n" +
				"left join\n" +
				"jms_demand_screen b\n" +
				"on a.did=b.did\n" +
				"where a.isValid='是' "+ whee.toString()+" order by b.modifyDate desc";
		List<Record> screenDetail = Db.find(sql, param.toArray());

		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("screenDetail", screenDetail);

		String templateFileName = PathKit.getRootClassPath() + "/tpl_imp_screen.xls";
		String filename = "demand_screen.xls";
		render(JxlsRender.me(templateFileName).filename(filename).beans(beans));

	}

	@Before(AuthorizeInterceptor.class)
	public void imp() {
		render("../demand_screen_imp.html");
	}


	public void impData() {
		String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
		UploadFile file = getFile();
		String fileName = null;
		if (file !=null) {
			File source = file.getFile();
			fileName = file.getFileName();
			try {
				FileInputStream fis = new FileInputStream(source);
				File targetDir = new File(PathKit.getWebRootPath()  + "/u/" + path);
				if (!targetDir.exists()) {
					targetDir.mkdirs();
				}
				File target = new File(targetDir, fileName);
				if (!target.exists()) {
					target.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(target);
				byte[] bts = new byte[300];
				while (fis.read(bts, 0, 300) != -1) {
					fos.write(bts, 0, 300);
				}
				fos.close();
				fis.close();
				source.delete();
				//1.清空临时表
				Db.update("delete a from imp_demand_screen a");
				String templateFileName = PathKit.getWebRootPath()  + "/u/" + path +"/" +fileName;
				//2.导入数据
				String sql = "insert into imp_demand_screen (did,cusName,city,homeCounty,name,longitude,latitude,aerialHeight," +
						"isSuccess,failMemo,isShare,shareName,longitude2,latitude2,addr," +
						"space,aerialHeight2,aerialCnt,towerType,room,buildType,memo) " +
						"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				Map<String, Object> map = PoiExt.ReadExcel(templateFileName, "站址筛查初步方案确认表", sql, 6, 1, 22);
				renderDWZSuccessJson("总记录数:"+map.get("count")+"；成功导入:"+map.get("success")+"；失败数"+map.get("lost"));
				//3.更新筛查结果
				List<Record> records =Db.find("select * from imp_demand_screen ");
				for(Record r:records) {
					sql="INSERT INTO jms_demand_screen (did,isSuccess,failMemo,isShare,shareName,longitude,latitude,addr,space,aerialHeight,aerialCnt,towerType,room,buildType,memo) \n" +
							"VALUES('"+r.get("did")+"','"+r.get("isSuccess")+"','"+r.get("faileMemo")+"','"+r.get("isShare")+"','"+r.get("shareName")+"',\n" +
							""+r.get("longitude2")+","+r.get("latitude2")+",'"+r.get("addr")+"','"+r.get("space")+"','"+r.get("aerialHeight2")+"',"+r.get("aerialCnt")+",\n" +
							"'"+r.get("towerType")+"','"+r.get("room")+"','"+r.get("buildType")+"','"+r.get("memo")+"')\n" +
							"ON DUPLICATE KEY UPDATE isSuccess='"+r.get("isSuccess")+"',failMemo='"+r.get("failMemo")+"',isShare='"+r.get("isShare")+"',shareName='"+r.get("shareName")+"',\n" +
							"longitude="+r.get("longitude2")+",latitude="+r.get("latitude2")+",addr='"+r.get("addr")+"',\n" +
							"space="+r.get("space")+",aerialHeight='"+r.get("aerialHeight2")+"',aerialCnt="+r.get("aerialCnt")+",\n" +
							"towerType='"+r.get("towerType")+"',room='"+r.get("room")+"',buildType='"+r.get("buildType")+"',memo='"+r.get("memo")+"'";
					Db.update(sql);
					/*更新筛查状态
					sql="update jms_demand a set a.isScreen='是' where did=?";
					Db.update(sql,r.get("did"));
					*/
				}
			} catch (FileNotFoundException e) {
				renderDWZErrorJson("上传出现错误，请稍后再上传");
			}catch (Exception e){
				renderDWZErrorJson("导入失败，请重新上传"+e.getMessage());
			}
		}

	}



	public void lookupDemand() {

		StringBuffer whee = new StringBuffer();
		List<Object> param = new ArrayList<Object>();
		String name = getPara("name");
		String homeCounty = getPara("homeCounty");

		if(ChristStringUtil.isNotEmpty(name)){
			whee.append(" and name like ?");
			param.add("%" + name + "%");
		}

		if(ChristStringUtil.isNotEmpty(homeCounty)){
			whee.append(" and homeCounty like ?");
			param.add("%" + homeCounty + "%");
		}

		Page<Demand> pager = Demand.dao.paginate(
				getParaToInt("pageNum", 1),
				getParaToInt("numPerPage", 20),
				"select * ",
				" from " + TABLE_Demand  +
						"  where 1=1"+ whee.toString() ,
				param.toArray()
		) ;

		setAttr("pager",pager);
		setAttr("name",name);
		setAttr("homeCounty",homeCounty);
		render("../demand_lookup.html");
	}


}
